//
//  MoreViewController.m
//  DataStatistics
//
//  Created by Kang on 15/8/20.
//  Copyright (c) 2015年 YTYangK. All rights reserved.
//

#import "MoreViewController.h"

#import "Webview.h"
//#import "Masonry.h"
#import "isPhoneNumber.h"
#import "LoginVC.h"
#import "MBProgressHUD.h"
#import "SearchVC.h"
#import "UserModel.h"
#import "UserViewModel.h"
#import "WarningView.h"
#import "AppDelegate.h"
#import "analysisview.h"
#import "GUAAlertView.h"
//#import "DeploySDK.h"
#import "JPUSH.h"


@interface MoreViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,YLZHoledViewDelegate>//UIViewControllerRestoration
{
    float W_and_H;
    BOOL _isLarge;
    WarningView *Wview;
    NSInteger hour;
    NSInteger minute;
    analysisview *Aview;
    
    // 控制按钮触发事件顺序
    BOOL isShowWview;
    
    YLZHoledView * _holdedView;
}

//页面布局全局变量
@property (weak, nonatomic) IBOutlet UIImageView *Warningimage;
@property (weak, nonatomic) IBOutlet UILabel *Timer;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *privacyH;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *privacyAndPasswordBtm;// 修改密码按钮
@property (strong,nonatomic) NSMutableDictionary *parameter;
@property (weak, nonatomic) IBOutlet UIButton *SetUp;
@property (weak, nonatomic) IBOutlet UILabel *warninglabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *service;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *password;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *PandC;
//@property (strong, nonatomic)
@end

@implementation MoreViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    self.restorationIdentifier = @"MDC_More";
    self.restorationClass = [self class];
    
    //开启监听中心
    [NSNC addObserver:self selector:@selector(reloadJpushData:) name:@"JPUSHNOTIFICATION" object:nil];
    [NSNC addObserver:self selector:@selector(reloadJpushData1:) name:@"JPUSHNOTIFICATION1" object:nil];
    [self updateUI];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self tap];

    CGRect viewBounds = self.view.bounds;
    CGFloat topBarOffset = -20.0;
    viewBounds.origin.y = -topBarOffset;
    self.view.bounds = viewBounds;
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self.navigationController setNavigationBarHidden:NO];
    
    [self dataRequest];
    [self NSLayoutConstraint];
    if ([[NSUD objectForKey:MDC_SET_MASKDATAVIEW] intValue] == 1) {
        if ([SearchVC sharedSearchVC].searchModelAry.count != 0) {
            [self addMaskView];
        }
    }
    
}


- (void)updateViewConstraints {
    [super updateViewConstraints];
    if (SCREEN_HEIGHT==480) {
    }
}



#pragma mark - 设置文字 
- (void)updateUI {
    isShowWview = NO;
    self.view.backgroundColor = RGB(33, 38, 44, 1);
    self.title = NSLocalizedString(@"CpvcLead_title", nil);
    
    [self.SetUp setTitle:NSLocalizedString(@"Contact Customer Service", @"联系客服") forState:UIControlStateNormal];

    UIButton * btn =  [self.privacyAndPasswordBtm objectAtIndex:1];
    [btn setTitle:NSLocalizedString(@"CpvcLead_pas", @"修改密码") forState:UIControlStateNormal];
    
    
    UIBarButtonItem *backIetm = [[UIBarButtonItem alloc] init];
    backIetm.title = NSLocalizedString(@"back", nil);
    self.navigationItem.backBarButtonItem = backIetm;

    
    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon-exit"] style:UIBarButtonItemStyleDone target:self action:@selector(tuichu)];
    self.navigationItem.rightBarButtonItem = leftBtn;

    UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Warning:)];
    [_Warningimage addGestureRecognizer:singleTap1];

}


//设置完报警时间后进行重新请求
- (void)reloadJpushData: (NSNotification *)sender{
    
    isShowWview = NO;
    self.Warningimage.image = [UIImage imageNamed:@"pic-gaojing-off"];
    
    // 删除教程
    NSLog(@"打印---%@",[NSUD objectForKey:MDC_SET_MASKVIEW]);
    if ([[NSUD objectForKey:MDC_SET_MASKVIEW] isEqualToString:@"加遮-1"] ) {
        [NSUD  setObject:nil forKey:MDC_SET_MASKVIEW];
        [NSUD  setBool:false forKey:MDC_SET_MASKDATAVIEW];
        [self removeMaskVeiw];
    }
    
    //延迟1.1秒获取数据
    double delayInSeconds = 1.1;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
        [self dataRequest];

    });
    
}


- (void)reloadJpushData1: (NSNotification *)sender{
     isShowWview = NO;
    self.Warningimage.image = [UIImage imageNamed:@"pic-gaojing-off"];
    [NSNC removeObserver:self name:@"JPUSHNOTIFICATION1" object:self];

}

#pragma mark - UIViewControllerRestoration
/*+ (nullable UIViewController *) viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder {
   // UIStoryboard *stord = [UIStoryboard storyboardWithName:@"Main" bundle:NULL];
   // [stord instantiateViewControllerWithIdentifier:@"more"];
    MoreViewController *vc = [[self alloc] init];
    vc.Timer = [coder decodeObjectForKey:@"MDC_timer"];//[[MoreViewController alloc] initWithNibName:@"MoreViewController" bundle:nil];
    return vc;
}

- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
    [super encodeRestorableStateWithCoder:coder];
    //数据保存
    [coder encodeObject:self.Timer.text forKey:@"MDC_timer"];
    //[coder encodeObject:self forKey:<#(nonnull NSString *)#>]
}
//数据恢复
- (void)decodeRestorableStateWithCoder:(NSCoder *)coder {
    [super decodeRestorableStateWithCoder:coder];
    self.Timer.text  = [coder decodeObjectForKey:@"MDC_timer"];
}

*/
- (IBAction)gotoChangePas:(id)sender {
     [self performSegueWithIdentifier:@"gotoChangePas" sender:self];
}
- (IBAction)gotoChangePasAction:(id)sender {
    if (isShowWview == NO) {
         [self performSegueWithIdentifier:@"gotoChangePas" sender:self];
    }
}



#pragma mark - 请求
- (void)dataRequest {
    
    [UserViewModel requestWithUrlForUser:self andParam:@{@"user_id":MDC_USERCODE} success:^(UserModel *model) {

        hour = model.Alarm/3600;
        minute = (model.Alarm%3600)/60;
        

        if (hour >=1&&minute>0) {
            NSString *str1 = [NSString stringWithFormat:@"%ld小时%ld分钟",(long)hour ,(long)minute];
            NSString *string = [NSString stringWithFormat:@"%ld",(long)hour];
            NSString *string1 = [NSString stringWithFormat:@"%ld",(long)minute];
            long len1 = [string length];
            long len2 = [string1 length];
            NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc]initWithString:str1];

            if (len1 == 2) {
            [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(0,len1)];
            [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(4,len2)];
            self.Timer.attributedText =str2;
            self.Timer.numberOfLines = 0;

                }else if(len1 == 1){

                    [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(0,len1)];
                    [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(3,len2)];
                    self.Timer.attributedText =str2;
                    self.Timer.numberOfLines = 0;

                }else if(len2 == 2){
                    [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(0,len1)];
                    [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(4,len2)];
                    self.Timer.attributedText =str2;
                    self.Timer.numberOfLines = 0;

                }else if (len2 ==1){
                    [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(0,len1)];
                    [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(3,len2)];
                    self.Timer.attributedText =str2;
                    self.Timer.numberOfLines = 0;

                }
                
        
        }else if (hour>=1){
            
            NSString *str1 =[NSString stringWithFormat:@"%ld小时",(long)hour];
            NSString *string = [NSString stringWithFormat:@"%ld",(long)hour];

            long len1 = [string length];
            NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc]initWithString:str1];

            if (len1 == 1) {
                
            [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(0,1)];
            self.Timer.attributedText =str2;
            self.Timer.numberOfLines = 0;

            }else{
                [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(0,2)];
                self.Timer.attributedText =str2;
                self.Timer.numberOfLines = 0;
            }
        }else{
            NSString *str1 = [NSString stringWithFormat:@"%ld分钟",(long)minute];
        
            NSString *string = [NSString stringWithFormat:@"%ld",(long)minute];
            
            long len1 = [string length];
            NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc]initWithString:str1];
            
            if (len1 == 1) {
                
                [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(0,1)];
                self.Timer.attributedText =str2;
                self.Timer.numberOfLines = 0;

            }else{
                
                [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(0,2)];
                self.Timer.attributedText =str2;
                self.Timer.numberOfLines = 0;

            }
            
        }

        // 删除通知
        [NSNC removeObserver:self name:@"JPUSHNOTIFICATION" object:self];
        [NSNC removeObserver:self name:@"JPUSHNOTIFICATION1" object:self];
        
    } failure:^(NSString *err) {
    }];
}

//拨打客服电话
- (IBAction)phone:(id)sender {
    if (isShowWview == NO) {
            UIWebView *callWebView = [[UIWebView alloc] init];
            
            NSURL *telURL = [NSURL URLWithString:@"tel:400-662-6806"];
            
            [callWebView loadRequest:[NSURLRequest requestWithURL:telURL]];
            
            [self.view addSubview:callWebView];
    }
}


//修改报警时间
- (void)Warning:(UITapGestureRecognizer *)tap{
    isShowWview = YES;
    Wview = [[NSBundle mainBundle]loadNibNamed:@"WarningView" owner:self options:nil][0];
    UIWindow *keyv=[[UIApplication sharedApplication] keyWindow];
    Wview.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    Wview.frame = CGRectMake(0, 0, keyv.frame.size.width, keyv.frame.size.height);
    [keyv addSubview:Wview];
    
    
    [UIView animateWithDuration:0.5 animations:^{
        Wview.alpha = 1;
        Wview.SetUpview.alpha = 1;
    }];
    
    
    
    //定位UIPickerView初始化位置
    [Wview.datepicker selectRow:hour inComponent:0 animated:NO];
    [Wview.datepicker selectRow:minute inComponent:1 animated:NO];

    
    self.Warningimage.image = [UIImage imageNamed:@"pic-gaojing-on"];
}



/* 退出登录 */
- (void)tuichu{
    
    self.navigationItem.rightBarButtonItem.enabled = NO;

    
    GUAAlertView *v = [GUAAlertView alertViewWithTitle:@"提示"
                                        message:NSLocalizedString(@"CpvcLead_2", @"退出提示")
                                           buttonTitle:NSLocalizedString(@"Log out", nil)
                                   buttonTouchedAction:^{
                                       NSLog(@"button touched");
                                       
                                       [MoreViewController logout:self];
                                       
                                       
                                   } dismissAction:^{
                                       NSLog(@"dismiss");
                                       self.navigationItem.rightBarButtonItem.enabled = YES;
      
                                   }];
    [v show];

}


/* 退出登录 */
+ (void)logout:(UIViewController *)VC {
    [MoreViewController logoutOnline:VC];
}
+ (void)moreAbnormalExit:(UIViewController *)vc {
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [MoreViewController removeMDCData];             /// 删除绑定的全部标签
    UIStoryboard * storyboard =[UIStoryboard storyboardWithName:@"Login" bundle:NULL];
    LoginVC *log              = [storyboard instantiateInitialViewController];
    UIWindow *window          = [UIApplication sharedApplication].keyWindow;
    [vc presentViewController:log animated:YES completion:^{
        window.rootViewController = log;
        [JPUSH sharedJPUSH].sonWindow = nil;
        [JPUSH sharedJPUSH].tabBarC = nil;
        [[JPUSH sharedJPUSH] Deleteaccount];
    }];
}



+ (void)logoutOnline:(UIViewController *)vc {
    /**
     *  退出登录请求方法
     */
    [UserViewModel requestWithUrlForlogoutOnline:self andParam:nil success:^(id model) {
        [MoreViewController moreAbnormalExit:vc];
    } failure:^(NSString *err) {
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:err toView:nil];
    }];
}


+ (void)removeMDCData{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [NSUD removeObjectForKey:MDC_TOKEN];
    [NSUD removeObjectForKey:MDC_USER_INFO_DIC];
    [NSUD removeObjectForKey:MDC_PASSWORD_VLUE];
    
    [NSNC removeObserver:BADGE_Home];
    [NSNC removeObserver:BADGE_Num];
    [NSNC removeObserver:UIApplicationDidBecomeActiveNotification];
    [NSNC removeObserver:MDC_SET_BADGE];
    [NSNC removeObserver:MDC_NOTIFICATION_NICK];
    [NSNC removeObserver:MDC_USERCODE];
    
    [[UIApplication sharedApplication] cancelAllLocalNotifications]; // 清除全部通知。
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; //角标清0
    
    [[SearchVC sharedSearchVC] removeMaskLayer];
    [[SearchVC sharedSearchVC] setSearchModelAry:nil];
    [[SearchVC sharedSearchVC].searchTableView reloadData];
}

- (void)NSLayoutConstraint
{
    
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        self.Wimage.constant = 230;
        self.Himage.constant = 230;
        self.NSLayout1.constant = 55;
        self.NSlayout2.constant = 25;
        self.Label1.constant = -161;
        self.label2.constant = -68;
        self.warninglabel.font = [UIFont boldSystemFontOfSize:16.f];
        self.password.constant = 43;
        self.service.constant = 43;
        self.PandC.constant = 8;
        
        self.SetUp.imageEdgeInsets = UIEdgeInsetsMake(2,-2,2,2);
        UIButton * btn =  [self.privacyAndPasswordBtm objectAtIndex:1];
        btn.imageEdgeInsets =UIEdgeInsetsMake(2,-2,2,2);
      
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"667.0")){
        
        self.NSLayout1.constant = 65;
        self.NSlayout2.constant = 40;

        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"736.0")){
        self.Wimage.constant = 315;
        self.Himage.constant = 315;
        self.NSLayout1.constant = 80;
        self.NSlayout2.constant = 55;
        self.Label1.constant = -200;
        self.label2.constant = -90;
        self.warninglabel.font = [UIFont boldSystemFontOfSize:20.f];
        self.password.constant = 53;
        self.service.constant = 53;
        self.PandC.constant = 15;
    }
}

//长按手势
-(void)tap
{
    self.longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGestures:)];
    self.longPressGestureRecognizer.numberOfTouchesRequired = 1;
    self.longPressGestureRecognizer.allowableMovement = 100.0f;
    self.longPressGestureRecognizer.minimumPressDuration = 1.0;
    [self.Warningimage addGestureRecognizer:self.longPressGestureRecognizer];
}


- (void)handleLongPressGestures:(UILongPressGestureRecognizer *)paramSender{
   
    if (paramSender.state == UIGestureRecognizerStateBegan){
        NSLog(@"Long PressGesture");
    
        Aview = [[NSBundle mainBundle]loadNibNamed:@"analysisview" owner:self options:nil][0];
        UIWindow *keyv=[[UIApplication sharedApplication] keyWindow];

        [keyv addSubview:Aview];
        

        if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
           
            Aview.frame = CGRectMake(34, 30, 250, 87);
            Aview.anlysislabel.font = [UIFont systemFontOfSize:13];
            Aview.anlysisL.constant = 35;

        }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"667.0")){
            Aview.frame = CGRectMake(47,35 , 280,95);
            Aview.anlysislabel.font = [UIFont systemFontOfSize:14];

            
        }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"736.0")){
            Aview.frame = CGRectMake(56,45 , 300, 105);
            Aview.anlysislabel.font = [UIFont systemFontOfSize:16];
        }
        self.Warningimage.image = [UIImage imageNamed:@"pic-gaojing-on"];

        
        [UIView animateWithDuration:4.0 // 动画时长
                              delay:0.0 // 动画延迟
             usingSpringWithDamping:0.3 // 类似弹簧振动效果 0~1
              initialSpringVelocity:3.0 // 初始速度
                            options:UIViewAnimationOptionCurveEaseInOut // 动画过渡效果
                         animations:^{
                             // code...
                             CGPoint point = Aview.center;
                             point.y += 10;
                             [Aview setCenter:point];
                             Aview.alpha = 1;
                             Aview.anlysisimage.alpha = 1;
                             Aview.anlysislabel.alpha = 1;
     
                         } completion:^(BOOL finished) {
                             // 动画完成后执行
                             // code...
                             
                            
                         }];
        

        }else if (paramSender.state == UIGestureRecognizerStateEnded){

            self.Warningimage.image = [UIImage imageNamed:@"pic-gaojing-off"];

        [UIView animateWithDuration:0.5 animations:^{

            Aview.alpha = 0;
            Aview.anlysisimage.alpha = 0;
            Aview.anlysislabel.alpha = 0;
        }completion:^(BOOL finished) {
            // 动画完成后执行
            // code...
            [Aview removeFromSuperview];
 
        }];
    }
}


- (void)holedView:(YLZHoledView *)holedView didSelectHoleAtIndex:(NSUInteger)index {
    if (index == 0) {
        if (holedView.tag == 110) {
            [self Warning:nil];
        }
    }
}


#pragma mrak - 其他
- (void)addMaskView {

    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2  - 90, SCREEN_HEIGHT/2 + 43, 180, 30)];
    [label setTextColor:[UIColor whiteColor]];
    [label setFont:[UIFont systemFontOfSize:18]];
    [label setText:@"点击按钮设置报警时间"];
    
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2 - 150, SCREEN_HEIGHT/2 -175 , 300,115)];
    imageView.image = [UIImage imageNamed:@"报警说明"];


    //CGRectMake(SCREEN_WIDTH/2 -  52, SCREEN_HEIGHT/2 - 32, 110, 40)
    CGRect rect;
    if (SCREEN_WIDTH == 320) {
       rect = CGRectMake(SCREEN_WIDTH/2 -  52, SCREEN_HEIGHT/2 - 32, 110, 40);
    }else if (SCREEN_WIDTH == 414) {
        rect = CGRectMake(SCREEN_WIDTH/2 - 66, SCREEN_HEIGHT/2 - 27.5, 140, 42);
    }else if (SCREEN_WIDTH == 375) {
        rect = CGRectMake(SCREEN_WIDTH/2 -  59, SCREEN_HEIGHT/2 - 34, 125, 40);
    }
    
    
   _holdedView = [UtilToolsClss teturnMaskViewForObj:self maskLayerRect:rect fingerPoint:CGPointMake(SCREEN_WIDTH/2 + 40, SCREEN_HEIGHT/2 + 25) setTag:110 layerRadius:15 andImage:[UIImage imageNamed:@"shouzhi1"] imageAry:@[[UIImage imageNamed:@"shouzhi2"],[UIImage imageNamed:@"shouzhi1"]]];
    
    [_holdedView addSubview:label];
    [_holdedView addSubview:imageView];
     _holdedView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.99];
    [[UIApplication sharedApplication].keyWindow addSubview:_holdedView];
}
- (void)removeMaskVeiw {
    [_holdedView removeFromSuperview];
     _holdedView = nil;
}



#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
//    if ([segue.identifier compare:@"pushRegister"] == NO) {
//        id vc = segue.destinationViewController;
//        [vc setValue:_signStr forKey:@"RAVCsignStr"];
//    }
}




@end
